#include "rc38.h"
#include "switch.h"

type_rc38 rc38_data;

void rc38_init(void)
{
  rc38_data.status = RC38_WAIT;
  GPIO_Init(RC38_PIN, GPIO_MODE_IN_PU_IT);
  EXTI_SetExtIntSensitivity(EXTI_PORT_GPIOD, EXTI_SENSITIVITY_FALL_ONLY);
  EXTI_SetTLISensitivity(EXTI_TLISENSITIVITY_FALL_ONLY);
  TIM2_TimeBaseInit(TIM2_PRESCALER_2048, 65535);
  TIM2_Cmd(ENABLE);
}

uint8_t rc38_get(void)
{
  return rc38_data.data.c[2]^rc38_data.data.c[3]==0xff?rc38_data.data.c[2]:0;
}

void rc38_fun(void)
{
  if(rc38_data.status != RC38_DONE)
  {
    return;
  }
  rc38_data.status = RC38_WAIT;
  if(rc38_data.data.c[0]!=0x80||rc38_data.data.c[1]!=0xbf)
  {
    return;
  }
  rc38_data.pc = rc38_data.data.c[2]^rc38_data.data.c[3];
  if(rc38_data.pc != 0xff)
  {
    return;
  }
  switch(rc38_data.data.c[2])
  {
  case  0x3b: switch_v(0); switch_km(0);        break;
  case  0x19: switch_v(1); switch_km(1);        break;
  case  0xa3: switch_v(2); switch_km(2);        break;
  case  0xa9: switch_v(3); switch_km(3);        break;
  case  0xa1: switch_addk();                    break;
  case  0x61: switch_subk();                    break;
  case  0x73: switch_auto();                    break;
  case  0x39: switch_v(0);                      break;
  }
}

void rc38_interrupt(void)
{  
  uint16_t temp = TIM2_GetCounter();
  uint16_t tim = temp-rc38_data.timer;
  if(rc38_data.status == RC38_WAIT)
  {
    // 106*0.128 = 13.58ms
    if(tim>101 && tim<111)
    {
      rc38_data.status = RC38_RX;
      rc38_data.pc = 0;
      rc38_data.data.i = 0;
    }
    rc38_data.timer = temp;
    return;
  }
  if(rc38_data.status == RC38_RX)
  {
    // 17.6*0.128 = 2.26ms 
    rc38_data.data.i <<= 1;
    if(tim>15 && tim<20)
    {
      rc38_data.data.i |= 0x01;
      rc38_data.pc++;
    }
    else
    {   
      // 8.86*0.128 = 1.13ms
      if(tim>7 && tim<11)
      {
        rc38_data.pc++;
      }
      else
      {
        rc38_data.status = RC38_WAIT;
      }
    }
    if(rc38_data.pc==0x20)
    {
      rc38_data.status = RC38_DONE;
    }
    rc38_data.timer = temp;
  }
}